import 'dart:io';

import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:flutter_demo/model/play_model.dart';
import 'package:flutter_demo/view/qz_dialog.dart';

import '../config/colors.dart';
import '../config/dimens.dart';
import '../util/utils.dart';

class RecordListView extends StatefulWidget {
  final List<String> records;
  final List<PlayModel> players;

  const RecordListView({
    Key key,
    this.records,
    this.players,
  }) : super(key: key);

  @override
  _RecordListViewState createState() => _RecordListViewState();
}

class _RecordListViewState extends State<RecordListView> {
  int lastIndex = -1;

  AudioPlayer audioPlayer = AudioPlayer();

  @override
  Widget build(BuildContext context) {
    return ListView.separated(
      itemCount: widget.players.length,
      shrinkWrap: true,
      itemBuilder: (BuildContext context, int i) {
        return buildContainer(i);
      },
      separatorBuilder: (BuildContext context, int index) {
        return Container(
          height: Dimens.dHeight2,
          color: Colours.lineColor,
        );
      },
    );
  }

  Container buildContainer(int i) {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.all(Dimens.dHeight29),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
            children: [
              InkWell(
                onTap: () {
                  _onPlay(filePath: widget.players
                      .elementAt(i)
                      .path, index: i);
                },
                child: Container(
                  width: Dimens.dWidth50,
                  height: Dimens.dWidth50,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(Dimens.dWidth50 * 0.5),
                    color: Colors.red,
                  ),
                  child: Icon(widget.players[i].playState == PlayState.isPlaying
                      ? Icons.pause
                      : Icons.play_arrow),
                ),
              ),
              Dimens.sizeBox_w23,
              Expanded(
                child: Container(
                  child: Text(
                    _getDateFromFilePatah(
                        filePath: widget.players
                            .elementAt(i)
                            .path),
                  ),
                ),
              ),
              InkWell(
                onTap: () {
                  deleteItem(widget.players[i].path,i);
                },
                child: Container(
                    width: Dimens.dWidth90,
                    height: Dimens.dHeight46,
                    child: Icon(
                      Icons.delete,
                      color: Colors.grey,
                      size: Dimens.dWidth32,
                    )),
              )
            ],
          ),
          Dimens.sizeBox_h28,
          Offstage(
            offstage: lastIndex != i,
            child: Container(
              width: double.infinity,
              child: Text(
                '${Utils.getDateFromMill(
                    widget.players[i].currentDuration)} / ${Utils
                    .getDateFromMill(widget.players[i].totalDuration)}',
                style: Dimens.style20_65,
              ),
            ),
          ),
          LinearProgressIndicator(
            minHeight: Dimens.dHeight6,
            backgroundColor: Colors.grey,
            valueColor: AlwaysStoppedAnimation<Color>(Colors.red),
            value: lastIndex == i
                ? widget.players[i].completedPercentage != null ? widget.players[i].completedPercentage : 0.0 : 0.0,
          ),
        ],
      ),
    );
  }

  Future<void> _onPlay({@required String filePath, @required int index}) async {
    if (lastIndex != index) {
      lastIndex = index;
    }

    if (widget.players[index].playState == PlayState.isPlaying) {
      audioPlayer.pause();
      widget.players[index].playState = PlayState.isPause;
    } else if (widget.players[index].playState == PlayState.isPause) {
      audioPlayer.resume();
      widget.players[index].playState = PlayState.isPlaying;
    } else {
      audioPlayer.stop();
      audioPlayer.play(filePath, isLocal: true);
      setState(() {
        widget.players[index].playState = PlayState.isPlaying;
        widget.players[index].currentDuration = 0;
      });
      audioPlayer.onPlayerCompletion.listen((_) {
        setState(() {
          widget.players[index].playState = PlayState.isStop;
          widget.players[index].currentDuration = 0;
          widget.players[index].completedPercentage = 0.0;
          lastIndex = -1;
        });
      });
      audioPlayer.onDurationChanged.listen((duration) {
        setState(() {
          widget.players[index].totalDuration = duration.inMilliseconds;
        });
      });

      audioPlayer.onAudioPositionChanged.listen((duration) {
        setState(() {
          widget.players[index].currentDuration = duration.inMilliseconds;
          widget.players[index].completedPercentage =
              duration.inMilliseconds / widget.players[index].totalDuration;
        });
      });
    }
    setState(() {});
  }

  String _getDateFromFilePatah({@required String filePath}) {
    if (!filePath.contains('.aac')) {
      return '123';
    }
    String fromEpoch = filePath.substring(
        filePath.lastIndexOf('/') + 1, filePath.lastIndexOf('.'));

    DateTime recordedDate =
    DateTime.fromMillisecondsSinceEpoch(int.parse(fromEpoch));
    int year = recordedDate.year;
    int month = recordedDate.month;
    int day = recordedDate.day;
    int hour = recordedDate.hour;
    int minutes = recordedDate.minute;
    int second = recordedDate.second;

    return ('$year-$month-$day-$hour:$minutes:$second');
  }

  deleteItem(String filePath,int index1) {
    FunctionUtil.popDialog(context, ShowAlertDialog(
      items: ['取消', '确认'],
      title: '提示',
      content: '确认删除本条记录吗？',
      onTap: (index) async {
        if (index == 1) {
          audioPlayer.stop();
            File file = File(filePath);
            file.deleteSync();
            widget.players.removeAt(index1);
            setState(() {
            });
        } else {
        }
      },));

  }
}
